package com.lqwu.mallchatserver.common.event.listener;

import com.lqwu.mallchatserver.common.event.UserApplyEvent;
import com.lqwu.mallchatserver.common.event.UserBlackEvent;
import com.lqwu.mallchatserver.user.model.entry.UserApply;
import com.lqwu.mallchatserver.user.service.UserApplyService;
import com.lqwu.mallchatserver.websocket.model.vo.response.data.WSFriendApply;
import com.lqwu.mallchatserver.websocket.service.WebSocketService;
import com.lqwu.mallchatserver.websocket.service.adapter.WSAdapter;
import com.lqwu.mallchatserver.websocket.service.adapter.WebSocketAdapter;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

/**
 * 用户好友申请监听器
 */
@Component
public class UserApplyListener {
    @Resource
    private WebSocketService webSocketService;
    @Resource
    private UserApplyService userApplyService;



    /**
     * 发送消息给前端
     * @param event
     */
    @Async
    @TransactionalEventListener(classes = UserApplyEvent.class,phase = TransactionPhase.AFTER_COMMIT)
    public void sendMsg(UserApplyEvent event) {
        UserApply userApply = event.getUserApply();
        // 获取目标用户的未读数量
        Integer unReadCount = userApplyService.getUnReadCount(userApply.getTargetId());
        // 发送消息给目标用户
        webSocketService.sendToUid(WSAdapter.buildApplySend(new WSFriendApply(userApply.getUid(), unReadCount)), userApply.getTargetId());
    }
}
